#include "form.h"
#include "ui_form.h"

Form::Form(QWidget *parent) : QWidget(parent), ui(new Ui::Form)
{
    ui->setupUi(this);
    this->initForm();

}

Form::~Form()
{
    delete ui;
}

QStringList getLocalIPs()
{
    static QStringList ips;
    if (ips.count() == 0) {
#ifdef emsdk
        ips << "127.0.0.1";
#else
        QList<QNetworkInterface> netInterfaces = QNetworkInterface::allInterfaces();
        foreach (const QNetworkInterface  &netInterface, netInterfaces) {
            //移除虚拟机和抓包工具的虚拟网卡
            QString humanReadableName = netInterface.humanReadableName().toLower();
            if (humanReadableName.startsWith("vmware network adapter") || humanReadableName.startsWith("npcap loopback adapter")) {
                continue;
            }

            //过滤当前网络接口
            bool flag = (netInterface.flags() == (QNetworkInterface::IsUp | QNetworkInterface::IsRunning | QNetworkInterface::CanBroadcast | QNetworkInterface::CanMulticast));
            if (flag) {
                QList<QNetworkAddressEntry> addrs = netInterface.addressEntries();
                foreach (QNetworkAddressEntry addr, addrs) {
                    //只取出IPV4的地址
                    if (addr.ip().protocol() == QAbstractSocket::IPv4Protocol) {
                        QString ip4 = addr.ip().toString();
                        if (ip4 != "127.0.0.1") {
                            ips.append(ip4);
                        }
                    }
                }
            }
        }
#endif
    }

    return ips;
}

QString getLocalIP()
{
    //优先取192开头的IP,如果获取不到IP则取127.0.0.1
    QString ip = "127.0.0.1";
    QStringList ips = getLocalIPs();
    foreach (QString str, ips) {
        if (str.startsWith("192.168.1") || str.startsWith("192")) {
            ip = str;
            break;
        }
    }

    return ip;
}


void Form::initForm()
{
    isOk = false;
    m_server = new TcpServer(this);

    connect(m_server, &TcpServer::clientConnected, this, &Form::clientConnected);
    connect(m_server, &TcpServer::clientDisconnected, this, &Form::clientDisconnected);
    connect(m_server, &TcpServer::sendData, this, &Form::sendData);
    connect(m_server,  &TcpServer::receiveData, this, &Form::receiveData);

    //获取本机所有IP
    QStringList ips = getLocalIPs();
    ui->cboxListenIP->addItems(ips);
    if (!ips.contains("127.0.0.1")) {
        ui->cboxListenIP->addItem("127.0.0.1");
    }
}


void Form::append(int type, const QString &data, bool clear)
{
    static int currentCount = 0;
    static int maxCount = 100;

    if (clear) {
        ui->txtMain->clear();
        currentCount = 0;
        return;
    }

    if (currentCount >= maxCount) {
        ui->txtMain->clear();
        currentCount = 0;
    }

    //过滤回车换行符
    QString strData = data;
    strData = strData.replace("\r", "");
    strData = strData.replace("\n", "");

    //不同类型不同颜色显示
    QString strType;
    if (type == 0) {
        strType = "发送";
        ui->txtMain->setTextColor(QColor("darkgreen"));
    } else {
        strType = "接收";
        ui->txtMain->setTextColor(QColor("red"));
    }

    //strData = QString("时间[%1] %2: %3").arg(TIMEMS).arg(strType).arg(strData);
    ui->txtMain->append(strData);
    currentCount++;
}

void Form::clientConnected(const QString &ip, int port)
{
    QString str = QString("%1:%2").arg(ip).arg(port);
    ui->listWidget->addItem(str);
    ui->labCount->setText(QString("共 %1 个客户端").arg(ui->listWidget->count()));
}

void Form::clientDisconnected(const QString &ip, int port)
{
    int row = -1;
    QString str = QString("%1:%2").arg(ip).arg(port);
    for (int i = 0; i < ui->listWidget->count(); i++) {
        if (ui->listWidget->item(i)->text() == str) {
            row = i;
            break;
        }
    }

    delete ui->listWidget->takeItem(row);
    ui->labCount->setText(QString("共 %1 个客户端").arg(ui->listWidget->count()));
}

void Form::sendData(const QString &ip, int port, const QString &data)
{
    QString str = QString("[%1:%2] %3").arg(ip).arg(port).arg(data);
    bool error = (data.contains("下线") || data.contains("离线"));
    append(error ? 1 : 0, str);
}

void Form::receiveData(const QString &ip, int port, const QString &data)
{
    //显示收到的数据
    QString str = QString("[%1:%2] %3").arg(ip).arg(port).arg(data);
    append(1, str);
}

void Form::on_btnListen_clicked()
{
    if (ui->btnListen->text() == "监听") {
        bool ok = true;
        QString str = ui->txtListenPort->text();
        int num = str.toInt(&ok, 10);

        isOk = m_server->start(ui->cboxListenIP->currentText(), num);
        if (isOk) {
            append(0, "监听成功");
            ui->btnListen->setText("关闭");
        }
    } else {
        isOk = false;
        m_server->stop();
        ui->btnListen->setText("监听");
    }
}


void Form::on_btnClear_clicked()
{
    append(0, "", true);
}

void Form::on_btnSend_clicked()
{
    if (!isOk) {
        return;
    }

    QString data = ui->cboxData->currentText();
    qDebug()<<"输入框要发送的数据:"<<data;

    if (data.length() <= 0) {
        return;
    }

    if (ui->ckSelectAll->isChecked()) {//全部发送
        m_server->writeData(data);
    } else {//指定发送
        int row = ui->listWidget->currentRow();
        if (row >= 0) {
            QString str = ui->listWidget->item(row)->text();
            QStringList list = str.split(":");
            m_server->writeData(list.at(0), list.at(1).toInt(), data);
        }
    }
}

void Form::on_btnClose_clicked()
{
    if (ui->ckSelectAll->isChecked()) {
        m_server->remove();
    } else {
        int row = ui->listWidget->currentRow();
        if (row >= 0) {
            QString str = ui->listWidget->item(row)->text();
            QStringList list = str.split(":");
            m_server->remove(list.at(0), list.at(1).toInt());
        }
    }
}
